let allTags = []; // 存储所有标签数据

// 从API获取所有标签
async function fetchAllTags() {
    try {
        const response = await fetch('/api/gettags/');
        if (response.ok) {
            allTags = await response.json();
            return allTags;
        } else {
            console.error('获取标签失败:', response.status);
            return [];
        }
    } catch (error) {
        console.error('获取标签失败:', error);
        return [];
    }
}

// 填充标签选择下拉框
function populateTagSelect(tags) {
    const select = document.getElementById('addTagSelect');
    // 清空现有选项（除了第一个选项）
    while (select.options.length > 1) {
        select.remove(1);
    }

    // 添加标签选项
    tags.forEach(tag => {
        const option = document.createElement('option');
        option.value = tag.name;
        option.setAttribute('data-type', tag.tag_type);
        option.textContent = `${tag.name} (${getTagTypeDisplay(tag.tag_type)})`;
        select.appendChild(option);
    });
}

// 获取标签类型显示名称
function getTagTypeDisplay(tagType) {
    const typeMap = {
        'BOOL': '布尔值',
        'INT': '整数',
        'STR': '字符串',
        'FLOAT': '浮点数',
        'DATE': '日期'
    };
    return typeMap[tagType] || tagType;
}

// 检查用户权限
async function checkAdminPermission() {
    try {
        const response = await fetch('/api/isadmin/');
        const data = await response.json();
        return data.ok;
    } catch (error) {
        console.error('检查权限失败:', error);
        return false;
    }
}

// 切换显示状态
async function toggleDisplay(imageId) {
    // if (!confirm('确定要切换图片的显示状态吗？')) return;
    
    try {
        const response = await fetch('/api/switchdisplay/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                id: imageId
            })
        });
        
        if (response.ok) {
            // alert('操作成功');
            // 更新状态显示
            const statusBadge = document.getElementById('display-status');
            const isCurrentlyPublic = statusBadge.textContent === '公开';
            statusBadge.textContent = isCurrentlyPublic ? '隐藏' : '公开';
            statusBadge.className = isCurrentlyPublic ? 'status-badge status-hidden' : 'status-badge status-public';
            location.reload();
        } else {
            alert('操作失败');
        }
    } catch (error) {
        console.error('切换显示状态失败:', error);
        alert('操作失败');
    }
}

// 显示编辑UI（如果有权限）
async function initEditUI() {
    const isAdmin = await checkAdminPermission();
    if (isAdmin) {
        document.querySelectorAll('.admin-only').forEach(el => {
            el.style.display = 'block';
        });

        // 加载标签数据
        const tags = await fetchAllTags();
        populateTagSelect(tags);
    }
}

// 根据标签类型生成对应的输入框
function createInputByType(tagType, currentValue = '') {
    const container = document.createElement('div');

    switch (tagType) {
        case 'BOOL':
            const boolValue = currentValue === 'True' || currentValue === 'true' || currentValue === true;
            container.innerHTML = `
                        <select class="form-control" id="tagValueInput">
                            <option value="true" ${boolValue ? 'selected' : ''}>是</option>
                            <option value="false" ${!boolValue ? 'selected' : ''}>否</option>
                        </select>
                    `;
            break;
        case 'INT':
            container.innerHTML = `<input type="number" class="form-control" id="tagValueInput" value="${currentValue}">`;
            break;
        case 'FLOAT':
            container.innerHTML = `<input type="number" step="0.01" class="form-control" id="tagValueInput" value="${currentValue}">`;
            break;
        case 'DATE':
            // 处理日期格式
            let dateValue = currentValue;
            if (currentValue && typeof currentValue === 'string' && currentValue.includes('T')) {
                dateValue = currentValue.split('T')[0];
            }
            container.innerHTML = `<input type="date" class="form-control" id="tagValueInput" value="${dateValue}">`;
            break;
        case 'STR':
        default:
            container.innerHTML = `<input type="text" class="form-control" id="tagValueInput" value="${currentValue}">`;
            break;
    }

    return container;
}

// 编辑标签
function editTag(tagId, tagName, tagType, currentValue) {
    document.getElementById('editTagId').value = tagId;
    document.getElementById('editTagName').value = tagName;
    document.getElementById('editTagType').value = tagType;
    document.getElementById('editTagModalTitle').textContent = `编辑标签: ${tagName}`;

    const container = document.getElementById('editTagValueContainer');
    container.innerHTML = '';
    container.appendChild(createInputByType(tagType, currentValue));

    const modal = new bootstrap.Modal(document.getElementById('editTagModal'));
    modal.show();
}

// 保存标签
async function saveTag() {
    const tagId = document.getElementById('editTagId').value;
    const tagType = document.getElementById('editTagType').value;
    const valueInput = document.getElementById('tagValueInput');
    const value = valueInput.value;

    if (value === '') {
        alert('请输入标签值');
        return;
    }

    try {
        const response = await fetch('/api/alttag/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                id: tagId,
                value: value
            })
        });

        if (response.ok) {
            // alert('保存成功');
            location.reload();
        } else {
            alert('保存失败');
        }
    } catch (error) {
        console.error('保存失败:', error);
        alert('保存失败');
    }
}

// 删除标签
async function deleteTag(tagId) {
    if (!confirm('确定要删除这个标签吗？这个操作不可撤销！')) return;

    try {
        const response = await fetch('/api/deltag/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                id: tagId
            })
        });

        if (response.ok) {
            // alert('删除成功');
            location.reload();
        } else {
            alert('删除失败');
        }
    } catch (error) {
        console.error('删除失败:', error);
        alert('删除失败');
    }
}

// 显示添加标签模态框
function showAddTagModal() {
    const modal = new bootstrap.Modal(document.getElementById('addTagModal'));
    modal.show();
}

// 标签选择变化时更新输入框
function onTagSelectChange() {
    const select = document.getElementById('addTagSelect');
    const selectedOption = select.options[select.selectedIndex];
    const tagType = selectedOption.getAttribute('data-type');

    const container = document.getElementById('addTagValueContainer');
    container.innerHTML = '';

    if (tagType) {
        container.appendChild(createInputByType(tagType));
    } else {
        container.innerHTML = '<div class="loading">请先选择标签</div>';
    }
}

// 添加新标签
async function addNewTag() {
    const select = document.getElementById('addTagSelect');
    const tagName = select.value;
    const valueInput = document.getElementById('tagValueInput');
    const value = valueInput ? valueInput.value : '';

    if (!tagName) {
        alert('请选择标签');
        return;
    }

    if (value === '') {
        alert('请输入标签值');
        return;
    }

    try {
        const response = await fetch('/api/addtag/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                    picture: imageId,
                    name: tagName,
                    value: value
                })
            });

        if (response.ok) {
            // alert('添加成功');
            location.reload();
        } else {
            alert('添加失败');
        }
    } catch (error) {
        console.error('添加失败:', error);
        alert('添加失败');
    }
}

// 获取CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 初始化
document.addEventListener('DOMContentLoaded', function () {
    initEditUI();
});